<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="queryParams" class="form-inline">
        <el-form-item label="用户名">
          <el-input v-model="queryParams.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="queryParams.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <el-table
      v-loading="loading"
      :data="userList"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="userName" label="用户名" min-width="120" />
      <el-table-column label="头像" width="100" align="center">
        <template #default="scope">
          <el-avatar 
            v-if="scope.row.avatar" 
            :src="getImageUrl(scope.row.avatar)" 
            :size="40"
          />
          <el-avatar v-else :size="40" icon="UserFilled" />
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" width="120" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button size="small" @click="handleView(scope.row)">查看</el-button>
          <el-button 
            :type="scope.row.status === 1 ? 'danger' : 'success'" 
            size="small" 
            @click="handleToggleStatus(scope.row)"
          >
            {{ scope.row.status === 1 ? '停用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 用户详情对话框 -->
    <el-dialog
      title="用户详情"
      v-model="dialogVisible"
      width="500px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户ID">{{ detailForm.id }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ detailForm.userName }}</el-descriptions-item>
        <el-descriptions-item label="头像">
          <el-avatar 
            v-if="detailForm.avatar" 
            :src="getImageUrl(detailForm.avatar)" 
            :size="60"
          />
          <el-avatar v-else :size="60" icon="UserFilled" />
        </el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detailForm.phone }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="detailForm.status === 1 ? 'success' : 'danger'">
            {{ detailForm.status === 1 ? '启用' : '停用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailForm.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailForm.updateTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserPage, getUserDetail, saveOrUpdateUser } from '@/api/user'
import { handlePageResponse } from '@/utils/pagination'

// 用户列表
const userList = ref([])
// 总数据量
const total = ref(0)
// 加载状态
const loading = ref(false)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  userName: '',
  phone: ''
})

// 用户详情表单
const detailForm = ref({})
// 用户详情对话框可见性
const dialogVisible = ref(false)

// 获取图片URL
const getImageUrl = (imagePath) => {
  if (!imagePath) return ''
  return `/api/file/download?fileName=${imagePath}`
}

// 初始化数据
onMounted(async () => {
  await fetchData()
})

// 获取用户列表数据
const fetchData = async () => {
  loading.value = true
  try {
    const res = await getUserPage(queryParams)
    const { list, total: totalCount } = handlePageResponse(res)
    userList.value = list
    total.value = totalCount
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchData()
}

// 重置查询
const resetQuery = () => {
  queryParams.userName = ''
  queryParams.phone = ''
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchData()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  queryParams.pageNum = 1
  fetchData()
}

// 处理查看用户详情
const handleView = (row) => {
  detailForm.value = { ...row }
  dialogVisible.value = true
}

// 处理状态切换
const handleToggleStatus = (row) => {
  const statusText = row.status === 1 ? '停用' : '启用'
  ElMessageBox.confirm(
    `确认${statusText}用户 "${row.userName}" 吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const newStatus = row.status === 1 ? 0 : 1
      const updateData = { ...row, status: newStatus }
      await saveOrUpdateUser(updateData)
      ElMessage({
        type: 'success',
        message: `${statusText}成功!`
      })
      await fetchData()
    } catch (error) {
      console.error('更新用户状态失败:', error)
    }
  }).catch(() => {
    // 取消操作
  })
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  padding-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}
</style> 